package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {
    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String GET_PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        String result = HttpRequest.get(GET_OPENID_URL)
            .form("appid", appId)
            .form("secret", appSecret)
            .form("js_code", code)
            .form("grant_type", "authorization_code")
            .timeout(5000)
            .execute()
            .body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        log.info("获取opendId的结果 = " + jsonObject);
        String openId = jsonObject.getStr("openid");
        // 得不到openId 说明出错了
        if(StrUtil.isEmpty(openId)){
            throw new ServiceException("获取openId失败，请稍后重试");
        }
        return openId;
    }

    /**
     * 获取用户的手机号码
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhoneNumber(String phoneCode) {
        String url = GET_PHONE_URL + getAccessToken();
        // singletonMap 构建一个map，这个map仅能放下一个key,value
        Map<String, String> map = Collections.singletonMap("code", phoneCode);
        String result = HttpRequest.post(url)
            .body(JSONUtil.toJsonStr(map))
            .timeout(5000)
            .execute().body();
        log.info("获取手机号码的结果 = " + result);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String phone = jsonObject.getByPath("phone_info.purePhoneNumber", String.class);
        if(StrUtil.isEmpty(phone)){
            throw new ServiceException("获取手机号码失败，请稍后重试");
        }
        return phone;
    }

    /**
     * 获取微信授权 有效期为2小时
     * 优化：access_token缓存到redis，设置有效期为1小时50分钟
     *   获取是优先从redis取
     * @return
     */
    private String getAccessToken(){
        String body = HttpRequest.get(ACCESS_TOKEN_URL)
            .form("appid", appId)
            .form("secret", appSecret)
            .form("grant_type", "client_credential")
            .timeout(5000)
            .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        log.info("获取微信授权: {}", jsonObject);
        String accessToken = jsonObject.getStr("access_token");
        if(StrUtil.isEmpty(accessToken)){
            throw new ServiceException("获取微信授权失败，请稍后重试");
        }
        return accessToken;
    }
}
